package com.hlmedicals.app.conf.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartResolver;

import com.lostad.app.common.util.SpringUtil;
import com.lostad.app.common.util.Validator;
/**
 * 保证流关闭后可以继续从request中获取json
 * @author：sszvip@qq.com
 * @since ：2016年10月14日
 */
public class HttpServletRequestReplacedFilter implements Filter {
	// 用于创建MultipartHttpServletRequest  
	private MultipartResolver multipartResolver = null;  
	      
	@Override  
	public void init(FilterConfig arg0) throws ServletException {  
	    // 注入bean  
	    System.out.println("----------------HttpServletRequestReplacedFilter inited----------------------"+multipartResolver);
	}  
	@Override
	public void destroy() {

	}
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		ServletRequest requestWrapper = null;
		if (request instanceof HttpServletRequest) {
			
			HttpServletRequest httpServletRequest = (HttpServletRequest) request;
			String method = httpServletRequest.getMethod();
			String contentType = httpServletRequest.getContentType();
			if ("post".equals(method.toLowerCase()) && contentType!=null && contentType.toLowerCase().contains("application/json")) {
				requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);//为了支持在拦截器中处理json
			}else if (Validator.isNotEmpty(contentType) && contentType.contains("multipart/form-data"))  {
				if(multipartResolver==null){
					  multipartResolver = ((MultipartResolver)SpringUtil.getBean("multipartResolver"));  
				}
				requestWrapper = multipartResolver.resolveMultipart((HttpServletRequest) request);//为了支持在拦截器中从 request中获取getParameter参数
			}
		}

		if (null == requestWrapper) {
			chain.doFilter(request, response);
		} else {//存在拦截json的情况，inputstream已经被close，替换为自定义的request
			chain.doFilter(requestWrapper, response);
		}
	}


}